import {createRouter, createWebHashHistory} from "vue-router";
import UserHome from "@/components/UserHome.vue";
import ShowGoodList from "@/views/user/ShowGoodList.vue";

import index from "@/views/admin/Index.vue";
import GoodList from "@/views/admin/GoodList.vue";
import GoodReview from "@/views/admin/GoodReview.vue";
import ViolationHandle from "@/views/admin/ViolationHandle.vue";
import OrderList from "@/views/admin/OrderList.vue";
import AnnouncementManage from "@/views/admin/AnnouncementManage.vue";
import CommentManage from "@/views/admin/CommentManage.vue";
import ClassifyManage from "@/views/admin/ClassifyManage.vue";
import SearchManage from "@/views/admin/SearchManage.vue";
import PermissionSettings from "@/views/admin/PermissionSettings.vue";
import LogManagement from "@/views/admin/LogManagement.vue";
import UserInfo from "@/views/admin/UserInfo.vue";
import UserCommon from "@/views/admin/UserCommon.vue";

import OrderManagement from "@/components/shopping/OrderManagement.vue";
import Cart from "@/components/shopping/Cart.vue";
import AddressManagement from "@/components/shopping/AddressManagement.vue";
import Layout from "@/components/shopping/Layout.vue";
import AddGood from "@/views/user/AddGood.vue";
import ShowGood from "@/views/user/ShowGood.vue";
import ChatView from "@/components/message/ChatView.vue";
import HistoryView from "@/components/message/HistoryView.vue";
import Login from "@/views/user/Login.vue";
import Register from "@/views/user/Register.vue";
import OrderDetail from "@/components/shopping/OrderDetail.vue";
import Profile from "@/views/user/profile/Profile.vue";
import Password from "@/views/user/profile/Password.vue";
import UserMessage from "@/views/user/profile/UserMessage.vue";
import Delete from "@/views/user/profile/Delete.vue";
import MyGood from "@/views/user/MyGood.vue";
import Analysis from "@/views/admin/Analysis.vue";
import SystemNotice from "@/components/message/SystemNotice.vue";
import PaySuccess from "@/components/shopping/PaySuccess.vue";
import MyFavorite from "@/views/user/MyFavorite.vue";


const router = createRouter({

    history: createWebHashHistory(),

    //定义路由规则 项目中有那些页面
    routes: [
        {
            path: "/",
            component: Login,
            children: []
        },
        {
            // 用户账号：yyy     密码:yyy1234
            //管理员账号：admin1  密码：admin1
            path: '/login',
            component: Login,
            name: 'Login'
        },
        {
            path: '/register',
            component: Register,
            name: 'Register'
        },
        {
            path: '/userHome',
            component: UserHome,//二手市场主页
            children: [
                {
                    path: 'showGoodList', //展示商品列表
                    component: ShowGoodList,
                    name: 'ShowGoodList'
                },
                {
                    path: 'addGood',
                    component: AddGood,
                    name: 'AddGood'
                },
                {
                    path: 'showGood/:id',
                    name: 'ShowGood',
                    component: ShowGood
                },
                {
                    path: 'myGood',
                    name: 'MyGood',
                    component: MyGood
                },
                {
                    path: 'myFavorite',
                    name: 'MyFavorite',
                    component: MyFavorite
                },
                {
                    path: 'Layout', //个人交易信息中心
                    component: Layout,
                    children: [
                        {
                            path: '/AddressManagement', //地址管理
                            component: AddressManagement,
                            name: 'AddressManagement'
                        },
                        {
                            path: '/OrderManagement', //订单管理
                            component: OrderManagement,
                            name: 'OrderManagement'
                        },
                        {
                            path: '/Cart', //购物车管理
                            component: Cart,
                            name: 'Cart'
                        },
                    ]
                }, {
                    path: 'profile', //个人交易信息中心
                    component: Profile,
                    children: [
                        {
                            path: "password",
                            component: Password,
                            name: Password
                        },
                        {
                            path: "userMessage",
                            component: UserMessage,
                            name: UserMessage
                        },
                        {
                            path: "delete",
                            component: Delete,
                            name: Delete
                        }
                    ]
                },
                {
                    path: '/order/detail/:id', //订单详情页面
                    component: OrderDetail,
                    name: 'OrderDetail',
                },
                {
                    path: '/PaySuccess',
                    component: PaySuccess,
                    name: 'PaySuccess'
                },
                //聊天页面
                {
                    path: 'ChatView',
                    component: ChatView,
                    name: "ChatView",
                    children: [
                        {
                            path: '/HistoryView',
                            component: HistoryView,
                            name: 'HistoryView'
                        }
                    ]
                }

            ]

        },
        //后端管理主页面
        {
            path: '/index',
            component: index,
            name: index,
            redirect: '/Analysis',
            children: [
                {
                    //数据分析
                    path: '/Analysis',
                    component: Analysis,
                    name: 'Analysis'
                },
                {
                    //商品列表
                    path: '/GoodList',
                    component: GoodList,
                    name: 'GoodList'
                },
                {
                    //商品审核
                    path: '/GoodReview',
                    component: GoodReview,
                    name: 'GoodReview'
                },
                {
                    //违规处理
                    path: '/ViolationHandle',
                    component: ViolationHandle,
                    name: 'ViolationHandle'
                },
                {
                    //订单列表
                    path: '/OrderList',
                    component: OrderList,
                    name: 'OrderList'
                },
                {
                    //公告管理
                    path: '/AnnouncementManage',
                    component: AnnouncementManage,
                    name: 'AnnouncementManage'
                },
                {
                    //评论管理
                    path: '/CommentManage',
                    component: CommentManage,
                    name: 'CommentManage'
                },
                {
                    //分类管理
                    path: '/ClassifyManage',
                    component: ClassifyManage,
                    name: 'ClassifyManage'
                },
                {
                    //搜索管理
                    path: '/SearchManage',
                    component: SearchManage,
                    name: 'SearchManage'
                },
                {
                    //管理员管理
                    path: '/AdminManage',
                    component: UserInfo,
                    name: 'AdminManage'
                },
                {
                    //用户管理
                    path: '/UserManage',
                    component: UserCommon,
                    name: 'UserManage'
                },
                {
                    //权限设置
                    path: '/PermissionSettings',
                    component: PermissionSettings,
                    name: 'PermissionSettings'
                },
                {
                    //日志管理
                    path: '/LogManagement',
                    component: LogManagement,
                    name: 'LogManagement'
                }
            ]
        },
        //系统公告
        {
            path: '/SystemNotice',
            component: SystemNotice,
            name: 'SystemNotice'
        },
    ]
});

// JWT解析函数
function parseJwt(token) {
    try {
        const base64Url = token.split('.')[1];
        const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
        const jsonPayload = decodeURIComponent(atob(base64).split('').map(function (c) {
            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
        }).join(''));
        return JSON.parse(jsonPayload);
    } catch (error) {
        console.error('解析JWT时出错:', error);
        return null;
    }
}

//前置拦截器
router.beforeEach((to, from) => {
    // 获取token
    const token = sessionStorage.getItem("token");

    // 如果没有token且访问的不是登录/注册页面，则重定向到登录页
    if (!token && to.path !== '/login' && to.path !== '/register') {
        return {name: 'Login'};
    }

    // 如果有token，解析用户信息
    if (token) {
        const payload = parseJwt(token);
        if (payload) {
            const userType = payload.userType;

            // 根据用户类型和目标路由进行权限控制
            // 管理员路由前缀
            const isAdminRoute = to.path.startsWith('/index') || to.path.startsWith('/Analysis') ||
                to.path.startsWith('/GoodList') || to.path.startsWith('/GoodReview') ||
                to.path.startsWith('/ViolationHandle') || to.path.startsWith('/OrderList') ||
                to.path.startsWith('/AnnouncementManage') || to.path.startsWith('/CommentManage') ||
                to.path.startsWith('/ClassifyManage') || to.path.startsWith('/SearchManage') ||
                to.path.startsWith('/AdminManage') || to.path.startsWith('/UserManage') ||
                to.path.startsWith('/PermissionSettings') || to.path.startsWith('/LogManagement');

            // 用户路由前缀
            const isUserRoute = to.path.startsWith('/userHome') || to.path.startsWith('/order') ||
                to.path.startsWith('/Cart') || to.path.startsWith('/AddressManagement') ||
                to.path.startsWith('/OrderManagement') || to.path.startsWith('/ChatView') ||
                to.path.startsWith('/HistoryView') || to.path.startsWith('/SystemNotice') ||
                to.path.startsWith('/PaySuccess');

            // 管理员访问管理员页面，允许通过
            if (userType === 'admin' && isAdminRoute) {
                return true;
            }

            // 普通用户访问用户页面，允许通过
            if (userType === 'user' && isUserRoute) {
                return true;
            }

            // 管理员访问用户页面，重定向到管理员首页
            if (userType === 'admin' && isUserRoute) {
                return {path: '/index'};
            }

            // 普通用户访问管理员页面，重定向到用户首页
            if (userType === 'user' && isAdminRoute) {
                return {path: '/userHome/showGoodList'};
            }
        } else {
            // JWT解析失败，清除token并重定向到登录页
            sessionStorage.removeItem("token");
            return {name: 'Login'};
        }
    }

    // 默认允许通过
    return true;
})



//导出对象 让外部组件使用路由
export default router;

